package henu.innovation.utils;

import henu.innovation.entity.Exam;
import henu.innovation.service.ExamService;
import henu.innovation.service.TeacherService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@WebServlet("/uploadServlet")
public class UploadServlet extends HttpServlet {
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private ExamService examService;

//    servlet中使用service所必须的内容!!!
    public void init(ServletConfig config) throws ServletException{
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,config.getServletContext());
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        String user = request.getParameter("user");
        Exam exam = null;
        try {
            exam = teacherService.teacherFindExam(Integer.parseInt(request.getParameter("id")));
        }catch (Exception e){
            System.out.println("没有传参examid");
        }
        String examname = request.getParameter("examname");

        request.setCharacterEncoding("utf-8");
        //文件名中文乱码处理也可以如此写
//        upload.setHeaderEncoding("utf-8");

        //设置缓冲区大小与临时文件目录
        factory.setSizeThreshold(1024 * 1024 * 10);
        File uploadTemp = new File("C:\\");
        uploadTemp.mkdirs();
        factory.setRepository(uploadTemp);

        //设置单个文件大小限制
        upload.setFileSizeMax(1024 * 1024 * 10);
        //设置所有文件总和大小限制
        upload.setSizeMax(1024 * 1024 * 30);

        try {
            List<FileItem> list = upload.parseRequest(request);
            System.out.println(list);
            for (FileItem fileItem : list) {
                if (!fileItem.isFormField() && fileItem.getName() != null && !"".equals(fileItem.getName())) {
                    String fileName = fileItem.getName();
                    //利用UUID生成伪随机字符串，作为文件名避免重复
//                        String uuid= UUID.randomUUID().toString();
                    //获取文件后缀名
                    String suffix = fileName.substring(fileName.lastIndexOf("."));

                    //获取文件上传目录路径，在项目部署路径下的upload目录里。若想让浏览器不能直接访问到图片，可以放在WEB-INF下
                    String uploadPath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload");

                    uploadPath += "\\" + examname;

                    File file = null;

//                    完整目录：/WEB-INF/upload/试卷名/试卷名 存放试卷文件
                    if(user.equals("teacher")){
                        uploadPath += "\\" + examname;
                        exam.setExampaper("\\"+examname+"\\"+examname);
                        examService.update(exam);
                        file = new File(uploadPath);

                        //删除文件夹下原有文件
                        File f;
                        String[] tempList = file.list();
                        if(tempList != null){
                            for(String s:tempList){
                                f = new File(uploadPath+"\\"+s);
                                f.delete();
                            }
                        }
                    }else if (user.equals("student")){
//                    完整目录：/WEB-INF/upload/试卷名/学号姓名 存放学生上传文件
                        uploadPath += "\\" + request.getSession().getAttribute("studentnumber")+request.getSession().getAttribute("studentname");
                        file = new File(uploadPath);
                    }

                    System.out.println("uploadpath:" + uploadPath);
//                    文件不存在，创建目录
                    if(!file.exists()){
                        if(!file.mkdirs()){
                            request.setAttribute("message", "创建目录失败！！");
                            request.getRequestDispatcher("/message.jsp").forward(request,response);
                            return;
                        }
                    }
                    //写入文件到磁盘，该行执行完毕后，若有该临时文件，将会自动删除
//                        fileItem.write(new File(uploadPath,uuid+suffix));
//                    fileItem.write(new File(uploadPath, fileName.substring(0, fileName.lastIndexOf(".")) + suffix));
                    if(user.equals("teacher")){
                        fileItem.write(new File(uploadPath, examname + suffix));
                    }else if(user.equals("student")){
                        fileItem.write(new File(uploadPath, fileName.substring(0, fileName.lastIndexOf(".")) + suffix));
                    }
                    System.out.println("Write success");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

